import json
import requests as rq

with open('all_gynecological.txt','r') as fr:
    all = fr.read().split('\n')

# print(all)
line = 0
allHospitals = []
while line < len(all):
    thisHospital = []
    # print(line, len(all))
    if all[line] == '空降兵军医院':
        itemsThis = 21
    else:
        itemsThis = 22
    for i in range(0, itemsThis):
        thisHospital.append(all[line])
        line += 1
        if line >= len(all):
            break

    # print(thisHospital)
    allHospitals.append(thisHospital)

cfmName = []
cfmAddr = []

allC = []
for a in range(0, len(allHospitals)):
    print(a, len(allHospitals))
    thisH = allHospitals[a]
    if len(thisH) == 15:
        continue
    thisC = {}
    # for i in range(0, len(thisH)):
    #     print(i, thisH[i])
    if len(thisH) == 21:
        thisC['validity'] = thisH[1]
        thisC['normalPregnant'] = ('不' not in thisH[5])
        thisC['suspectConfirmedPregnant'] = ('不' not in thisH[7])
        thisC['normalPregnancyCheck'] = ('不' not in thisH[9])
        thisC['ultraB'] = ('不' not in thisH[11])
        thisC['deformityExclusion'] = ('不' not in thisH[13])
        thisC['delivery'] = ('不' not in thisH[15])
        thisC['naCheck'] = ('不' not in thisH[17])
        thisC['info'] = ''
        thisAddr = thisH[20]
    else:
        thisC['validity'] = thisH[1]
        thisC['normalPregnant'] = ('不' not in thisH[5])
        thisC['suspectConfirmedPregnant'] = ('不' not in thisH[7])
        thisC['normalPregnancyCheck'] = ('不' not in thisH[9])
        thisC['ultraB'] = ('不' not in thisH[11])
        thisC['deformityExclusion'] = ('不' not in thisH[13])
        thisC['delivery'] = ('不' not in thisH[15])
        thisC['naCheck'] = ('不' not in thisH[17])
        thisC['info'] = thisH[19]
        thisAddr = thisH[21]


    url = 'https://restapi.amap.com/v3/place/text?key=de1fb1729e2e4f6fb20d2e6ea3ac8e27' \
      '&keywords=' + thisAddr + '&types=090100|090200|090300|090400|090500&city=武汉市&children=0&offset=1&page=1&extensions=all'
    response = rq.get(url)
    result = response.json()
    usingTMap = False
    if thisH[0] == '武汉广发肿瘤医院':
        tencentUrl = 'http://apis.map.qq.com/ws/place/v1/search?boundary=region(武汉,0)&page_size=1&page_index=1' \
                     '&keyword=武汉广发肿医院&orderby=&key=NL7BZ-4EQCF-B2CJ4-NGQN5-LETB7-DYFPM'
        response = rq.get(url)
        result = response.json()
        usingTMap = True
    if len(result['pois']) == 0:
        url = 'https://restapi.amap.com/v3/place/text?key=de1fb1729e2e4f6fb20d2e6ea3ac8e27' \
              '&keywords=' + thisH[0] + '&types=090100|090200|090300|090400|090500&city=武汉市&children=0&offset=1&page=1&extensions=all'
        response = rq.get(url)
        result = response.json()
        if len(result['pois']) == 0:
            tencentUrl = 'http://apis.map.qq.com/ws/place/v1/search?boundary=region(武汉,0)&page_size=1&page_index=1' \
                         '&keyword=' + thisH[0] + '&orderby=&key=NL7BZ-4EQCF-B2CJ4-NGQN5-LETB7-DYFPM'
            response = rq.get(tencentUrl)
            result = response.json()
            usingTMap = True
    if usingTMap == False:
        for k, v in result['pois'][0].items():
            if v == []:
                result['pois'][0][k] = ''
    if usingTMap:
        fmt_addr = result['data'][0]['address']
        fmt_name = result['data'][0]['title']
        fmt_type1 = result['data'][0]['category'].split(':')[1]
        fmt_type2 = result['data'][0]['category'].split(':')[2]
        fmt_alias = ''
        fmt_district = result['data'][0]['ad_info']['district']
        fmt_lng = result['data'][0]['location']['lng']
        fmt_lat = result['data'][0]['location']['lat']
        fmt_tel = result['data'][0]['tel']
    # if notFound:
    #     print('NOT FOUND', thisH)
    #     fmt_addr = thisAddr
    #     fmt_name = thisH[0]
    #     fmt_type1 = ''
    #     fmt_type2 = ''
    #     fmt_alias = ''
    #     fmt_district = ''
    #     fmt_lng = '-999'
    #     fmt_lat = '-999'
    #     fmt_tel = ''
    else:
        fmt_addr = result['pois'][0]['address']
        fmt_name = result['pois'][0]['name']
        fmt_type1 = result['pois'][0]['type'].split(';')[1]
        fmt_type2 = result['pois'][0]['type'].split(';')[2]
        fmt_alias = result['pois'][0]['alias'].replace('|', '；')
        fmt_district = result['pois'][0]['adname']
        fmt_lng = result['pois'][0]['location'].split(',')[0]
        fmt_lat = result['pois'][0]['location'].split(',')[1]
        fmt_tel = result['pois'][0]['tel'].replace(';', '；')

    cfmName.append(fmt_name + '=====' + thisH[0])
    cfmAddr.append(fmt_addr + '=====' + thisAddr)

    addInfo = {'hospitalName': fmt_name,
     'hospitalAlias': fmt_alias,
     'tel_GaodeMapAPI': fmt_tel,
     'district': fmt_district,
     'address': fmt_addr,
     'type1': fmt_type1,
     'type2': fmt_type2,
     'lng': float(fmt_lng),
     'lat': float(fmt_lat)
     }

    thisC.update(addInfo)
    allC.append(thisC)

all = {'gynecologicalHospitals':[]}
all['gynecologicalHospitals'] = [allC]

with open('formattedGH3.json','w') as fw:
    fw.write(json.dumps(all, ensure_ascii=False, separators=(',',':')))
with open('cfm3.csv','w') as fw:
    for i in range(0, len(cfmName)):
        fw.write(str(i) + '\n' + cfmName[i] + '\n' + cfmAddr[i] + '\n\n')
